import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {Injectable} from '@angular/core';
import {LoginUser} from "../api";
import {Config} from "../api";
import {GnMessageService} from "geminis-ng";

@Injectable({
  providedIn: 'root'
})
export class LoginUserGuard implements CanActivate {

  constructor(private loginUser: LoginUser,
              private router: Router,
              private configManage: Config,
              private messageService: GnMessageService) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (!route.routeConfig.data || !route.routeConfig.data.authorize) {
      return true;
    }

    const expiredTime = new Date(this.loginUser.jwtExpire);
    if (expiredTime < new Date()) {
      this.router.navigate([this.configManage.loginUrl], {queryParams: {msg: '没有权限访问'}});
      return false;
    }

    if (this.loginUser.authorities.indexOf(route.routeConfig.data.authorize) >= 0) {
      return true;
    } else {
      this.messageService.error({message: '没有访问权限', error: null});
      return false;
    }
  }


}
